package com.china08.yxyapi.api.manage.tec.office.moments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.moments.YxyMoments;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.moments.YxyMomentsRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.util.JpushForMessageUtil;
import com.china08.yxyapi.util.JpushForNotificationUtil;
import com.china08.yxyapi.util.YxUserPointsUtilV3;

/**
 * 班级圈--发布
 * 
 * @author LiuWeidong
 *
 */
@CrossOrigin
@RestController
public class MomentsReleaseController extends YxyApiBaseController {

    private static final Logger LOGGER = Logger.getLogger(MomentsReleaseController.class);

    @Autowired
    private YxyMomentsRepository yxyMomentsRepository;

    @Autowired
    private YxUserPointsUtilV3 yxUserPointsUtilV3;

    @Autowired
    JdbcTemplate JdbcTemplate;

    @RequestMapping(value = "/api_yw/manage/tec/office/student/srh/release", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel, RespModel respModel) {

        YxyProfile yxyProfile = getProfile(request, response);

        String schoolId = yxyProfile.getSchoolId();// 学校ID
        String userId = yxyProfile.getId();// 用户ID
        String userNick = yxyProfile.getUserNick();// 昵称
        String userName = yxyProfile.getUsername();
        String avater = yxyProfile.getUserAvator();// 头像

        String styleIntro = reqModel.styleIntro;// 内容
        List<String> imageList = reqModel.imageList;// 图片
        List<clazz> classList = reqModel.classList;// 班级
        for (clazz cl : classList) {
            YxyMoments yxyMoments = new YxyMoments();
            yxyMoments.setClassId(cl.classId);
            yxyMoments.setClassNick(cl.className);
            yxyMoments.setSenderNick(userNick);
            yxyMoments.setSenderId(userId);
            yxyMoments.setAvatar(avater);
            yxyMoments.setSenderUsername(userName);
            yxyMoments.setSchoolId(schoolId);
            yxyMoments.setStyleIntro(styleIntro);
            yxyMoments.setIsShareAll(1);
            yxyMoments.setImgs(imageList);
            yxyMomentsRepository.save(yxyMoments);
        }
        yxUserPointsUtilV3.sendClassMessage(userId);
        RespModel model = new RespModel();
        model.setMessage("发布成功");

        // 所在班级对应的老师
        StringBuffer sb1 = new StringBuffer();
        sb1.append("  SELECT                                     ");
        sb1.append("    teacher_id                               ");
        sb1.append("  FROM                                       ");
        sb1.append("    china08_yunxiao_pro.rel_class_teacher    ");
        sb1.append("  WHERE class_id IN                          ");
        sb1.append("    (SELECT                                  ");
        sb1.append("      class_id                               ");
        sb1.append("    FROM                                     ");
        sb1.append("   china08_yunxiao_pro.rel_class_teacher     ");
        sb1.append("    WHERE teacher_id = ?)                    ");
        sb1.append("  GROUP BY teacher_id                        ");
        List<Map<String, Object>> teaMapList = JdbcTemplate.queryForList(sb1.toString(), new Object[] { userId });

        // 老师的id
        List<String> teachersLst = new ArrayList<String>();
        String teaId = null;
        for (Map<String, Object> teaMap : teaMapList) {
            teaId = teaMap.get("teacher_id") + "";
            teachersLst.add(teaId);
        }

        // 对应的家长id
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT                                           ");
        sb.append("   guar.guardian_id                               ");
        sb.append(" FROM                                             ");
        sb.append("   china08_yunxiao_pro.rel_class_teacher tea,     ");
        sb.append("   china08_yunxiao_pro.app_student stu,           ");
        sb.append("   china08_yunxiao_pro.rel_student_guardian guar  ");
        sb.append("  WHERE tea.teacher_id = ?                        ");
        sb.append("   AND tea.class_id = stu.owner_class_id          ");
        sb.append("   AND stu.id = guar.student_id                   ");
        sb.append(" GROUP BY guar.guardian_id                        ");
        List<Map<String, Object>> guarMapList = JdbcTemplate.queryForList(sb.toString(), new Object[] { userId });

        String guarId = null;
        List<String> parentsLst = new ArrayList<String>();
        for (Map<String, Object> map : guarMapList) {
            guarId = map.get("guardian_id") + "";
            parentsLst.add(guarId);
        }

        // 发送消息
        List<Integer> roleIdList = new ArrayList<>();
        roleIdList.add(0);
        roleIdList.add(1);

        JpushForMessageUtil.sendMessage(5, roleIdList, schoolId, teachersLst, null);
        JpushForMessageUtil.sendMessage(5, roleIdList, schoolId, parentsLst, null);

        // 发送通知
        Map<String, String> mapNotification = new HashMap<String, String>();
        mapNotification.put("modelId", "classMoments");
        List<String> tabAndList1 = new ArrayList<>();
        tabAndList1.add("TEACHER" + schoolId);

        List<String> tabAndList2 = new ArrayList<>();
        tabAndList2.add("PARENTS" + schoolId);

        JpushForNotificationUtil.sendNotification(reqModel.styleIntro, "班级圈", mapNotification, teachersLst, tabAndList1);
        JpushForNotificationUtil.sendNotification(reqModel.styleIntro, "班级圈", mapNotification, parentsLst, tabAndList2);

        return model;
    }

    public static class clazz {
        public String classId;
        public String className;
    }

    protected static class ReqModel extends YxyApiPageReqModel {

        public List<clazz> classList;
        public List<String> imageList;
        public String styleIntro;

        @Override
        public void autoCheck() {
            Assert.isTrue(classList.size() > 0, "请选择班级");
            Assert.isTrue(StringUtils.isNotBlank(styleIntro), "内容不能为空");
        }
    }

    protected static class RespModel extends YxyApiRespModel {
    }

}
